<!-- @format -->
<template>
	<div>
		<el-button @click="show" type="default">
			<slot/>
		</el-button>
		<el-dialog title="位置选择" v-model="openMap" width="900px" append-to-body>
			<el-form label-width="80px">
				<el-row>
					<el-col :span="10">
						<el-form-item label="搜索地址">
							<el-autocomplete v-model="searchAddresKeywords" placeholder="请输入内容" :fetch-suggestions="querySearch" @select="mySelect" style="width: 100%">
							</el-autocomplete>
						</el-form-item>
					</el-col>
					<el-col :span="14">
						<el-form-item label="当前地址">
							<el-text class="mx-1" type="primary" style="color: #3d7fff">{{ addressInfo.address }}</el-text>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<div id="container" style="width: 100%; height: 600px"></div>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="confirmSelect">确 定</el-button>
				<el-button @click="cancel">取 消</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script setup name="TMapAddressSelect">
import tMap from "@/utils/tMap";

const defaultLat = 27.56955;
const defaultLng = 110.001668;

const props = defineProps({
	// 纬度
	lat: {
		type: [Number, String]
	},
	// 经度
	lng: {
		type: [Number, String]
	},
});

const emit = defineEmits(["confirm", "cancel"]);

// 搜索信息
let searchAddresKeywords = ref(null);
watch(searchAddresKeywords, (newValue, preValue) => {
	suggest
		.getSuggestions({
			keyword: newValue,
			location: map.getCenter(),
			servicesk: tMap.sk,
		})
		.then((res) => {
			suggestionList = [];
			res.data.forEach((item) => {
				item.value = item.title;
				item.data = item.title;
				suggestionList.push(item);
			});
		});
});

// 地址信息
let addressInfo = reactive({
	lat: props.lat, // 纬度
	lng: props.lng, // 经度
	province: "", // 省
	city: "", // 市
	district: "", // 区
	address: "", // 详细地址
});

const openMap = ref(false);

let map = null;
let geocoder = null;
let markerLayer = null;
let suggest = null;
let suggestionList = [];

const geocoderloc = function (loc, item) {
	map.panTo(loc);
	//添加marker
	markerLayer.remove("marker");
	markerLayer.add({
		id: "marker",
		position: loc,
	});
	if (item) {
		addressInfo.lng = item.location.lng;
		addressInfo.lat = item.location.lat;
		addressInfo.province = item.province;
		addressInfo.city = item.city;
		addressInfo.district = item.district;
		addressInfo.address = item.data;
	} else {
		geocoder
			.getAddress({
				location: loc,
				servicesk: tMap.sk,
			})
			.then((res) => {
				addressInfo.lng = res.result.location.lng;
				addressInfo.lat = res.result.location.lat;
				addressInfo.province = res.result.address_component.province;
				addressInfo.city = res.result.address_component.city;
				addressInfo.district = res.result.address_component.district;
				addressInfo.provinceCode = res.result.ad_info.adcode?.substring(0, 2) + "0000";
				addressInfo.cityCode = res.result.ad_info.adcode?.substring(0, 4) + "00";
				addressInfo.districtCode = res.result.ad_info.adcode;
				addressInfo.address = res.result.formatted_addresses?.recommend;
			});
	}
};

const mySelect = function (item) {
	geocoderloc(item.location, item);
};

const querySearch = function (queryString, cb) {
	cb(suggestionList);
};

// 初始化地图
const initMap = function (callBack) {
	if (map) {// 地图已经初始化
		callBack && callBack();
		return;
	}
	nextTick(() => {
		tMap.loadMap().then(() => {
			if (!(addressInfo.lat && addressInfo.lng)) {
				addressInfo.lat = defaultLat;
				addressInfo.lng = defaultLng;
			}
			// 地图对象
			let center = new TMap.LatLng(
				parseFloat(addressInfo.lat),
				parseFloat(addressInfo.lng)
			);
			map = new TMap.Map("container", {
				center: center,
				zoom: 12,
			});

			//初始化marker图层
			markerLayer = new TMap.MultiMarker({
				id: "marker-layer",
				map: map,
				geometries: [],
			});
			markerLayer.add({
				id: "marker",
				position: center,
			});

			// 新建一个关键字输入提示类
			suggest = new TMap.service.Suggestion({
				pageSize: 10, // 返回结果每页条目数
				region: "", // 限制城市范围
				regionFix: false, // 搜索无结果时是否固定在当前城市
			});

			// 新建一个正逆地址解析类
			geocoder = new TMap.service.Geocoder();
			geocoderloc(center);
			//监听点击事件
			map.on("click", (evt) => {
				geocoderloc(evt.latLng);
			});
			callBack && callBack();
		});
	});
};

// 打开地图选择
const show = function () {
	initMap(() => geocoderloc(new TMap.LatLng(props.lat || defaultLat, props.lng || defaultLng)));
	openMap.value = true;
};

// 确定选择
const confirmSelect = function () {
	emit("confirm", {...addressInfo});
	openMap.value = false;
};

// 取消选择
const cancel = function () {
	// geocoderloc(new TMap.LatLng(props.lat, props.lng));
	emit("cancel");
	openMap.value = false;
};

</script>

<style lang="scss" scoped>
.dialog-footer {
	margin-top: 12px;
	text-align: right;
}

#container {
	border-radius: 4px;
	overflow: hidden;
}
</style>
